package com.kinghood.productcenter.service.base.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kinghood.infrastructure.model.KingHoodException;
import com.kinghood.infrastructure.model.constant.CommonConstants;
import com.kinghood.infrastructure.util.UserUtil;
import com.kinghood.infrastructure.util.base.IdGenUtil;
import com.kinghood.productcenter.common.model.dao.product.BaseAttributeGroupDO;
import com.kinghood.productcenter.common.model.dto.base.AttributeGroupReqDTO;
import com.kinghood.productcenter.common.model.vo.base.AttributeGroupVO;
import com.kinghood.productcenter.dao.base.BaseAttributeGroupMapper;
import com.kinghood.productcenter.service.base.IBaseAttributeGroupService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性分租 服务实现类
 * </p>
 *
 * @author KingHood
 * @since 2023-12-26
 */
@Service
public class BaseAttributeGroupServiceImpl extends ServiceImpl<BaseAttributeGroupMapper, BaseAttributeGroupDO> implements IBaseAttributeGroupService {

    /**
     * 列表属性组
     *
     * @author jp
     * @date 2023/12/26
     */
    @Override
    public List<AttributeGroupVO> listAttributeGroup(AttributeGroupReqDTO param) {
        List<AttributeGroupVO> allData = this.baseMapper.getAllData(param);
        return allData.stream().filter(tree -> Objects.isNull(tree.getPid()))
                .peek((dept) -> dept.setChildren(getChildrenNode(dept, allData))).collect(Collectors.toList());
    }

    /**
     * 获取子节点
     *
     * @param dept    dept
     * @param dtoList dto列表
     * @author jp
     * @date 2023/12/26
     */
    private List<AttributeGroupVO> getChildrenNode(AttributeGroupVO dept, List<AttributeGroupVO> dtoList) {
        return dtoList.stream().filter((tree) -> Objects.nonNull(tree.getPid()) && tree.getPid().equals(dept.getId()))
                .peek((tree) -> tree.setChildren(getChildrenNode(tree, dtoList))).collect(Collectors.toList());
    }

    /**
     * 新增更新属性组
     *
     * @param param 参数
     * @author jp
     * @date 2023/12/26
     */
    @Override
    public void addorUpdateAttributeGroup(AttributeGroupReqDTO param) {
        checkOnly(param);
        BaseAttributeGroupDO group = new BaseAttributeGroupDO();
        BeanUtils.copyProperties(param, group);
        if (Objects.isNull(param.getId())) {
            group.setId(IdGenUtil.get().nextId());
            group.setCreateTime(LocalDateTime.now());
            group.setCreateUserId(UserUtil.getUserId());
            group.setUpdateTime(group.getCreateTime());
            group.setUpdateUserId(group.getCreateUserId());
            setPath(param, group);
            this.save(group);
        } else {
            group.setUpdateTime(LocalDateTime.now());
            group.setUpdateUserId(UserUtil.getUserId());
            setPath(param, group);
            this.updateById(group);
        }
    }

    /**
     * 设置路径
     *
     * @param param 参数
     * @param group 组
     * @author jp
     * @date 2023/12/26
     */
    private void setPath(AttributeGroupReqDTO param, BaseAttributeGroupDO group) {
        if (Objects.nonNull(param.getPid())) {
            BaseAttributeGroupDO parent = this.lambdaQuery().eq(BaseAttributeGroupDO::getId, param.getPid())
                    .eq(BaseAttributeGroupDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .one();
            if (Objects.isNull(parent)) {
                throw new KingHoodException(-1, "上级分组不存在");
            }
            group.setIdPath(parent.getIdPath()+"/"+ group.getId());
            group.setNamePath(parent.getNamePath()+"/"+ group.getGroupName());
        } else {
            group.setIdPath(group.getId()+"");
            group.setNamePath(group.getGroupName());
        }
    }

    /**
     * 删除属性组
     *
     * @param id id
     * @author jp
     * @date 2023/12/26
     */
    @Override
    public void delAttributeGroupById(Long id) {
        long childNum = this.lambdaQuery().eq(BaseAttributeGroupDO::getPid, id)
                .eq(BaseAttributeGroupDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .count();
        if (childNum > 0) {
            throw new KingHoodException(-1 , "存在子分组，不能删除");
        }
        int attributeNum = this.baseMapper.countAttributeByGroupId(id);
        if (attributeNum > 0) {
            throw new KingHoodException(-1 , "当前分组下存在属性，不能删除");
        }
        this.lambdaUpdate().set(BaseAttributeGroupDO::getIsDelete, CommonConstants.IS_DELETE_Y)
                .set(BaseAttributeGroupDO::getUpdateTime, LocalDateTime.now())
                .set(BaseAttributeGroupDO::getUpdateUserId, UserUtil.getUserId())
                .eq(BaseAttributeGroupDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .eq(BaseAttributeGroupDO::getId, id)
                .update();
    }

    /**
     * 详细
     *
     * @param id id
     * @author jp
     * @date 2023/12/26
     */
    @Override
    public AttributeGroupVO detailAttributeGroup(Long id) {
        BaseAttributeGroupDO data = this.lambdaQuery().eq(BaseAttributeGroupDO::getId, id)
                .eq(BaseAttributeGroupDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .one();
        AttributeGroupVO result = new AttributeGroupVO();
        BeanUtils.copyProperties(data, result);
        return result;
    }

    /**
     * 检查是否唯一
     *
     * @param param 参数
     * @author jp
     * @date 2023/12/21
     */
    private void checkOnly(AttributeGroupReqDTO param){
        Long count = 0l;
        if (Objects.isNull(param.getId())) {
            count = this.lambdaQuery().eq(BaseAttributeGroupDO::getGroupName, param.getGroupName())
                    .eq(BaseAttributeGroupDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .count();
            if (count > 0) {
                throw new KingHoodException(-1 ,"名称已存在");
            }
        } else {
            count = this.lambdaQuery().eq(BaseAttributeGroupDO::getGroupName, param.getGroupName())
                    .ne(BaseAttributeGroupDO::getId, param.getId())
                    .eq(BaseAttributeGroupDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .count();
            if (count > 0) {
                throw new KingHoodException(-1 ,"名称已存在");
            }
        }
    }
}
